import {observable, action, computed} from 'mobx';
import objectAssign from 'object-assign';
import {message} from 'antd';
import {WeaTools} from 'ecCom';
import {getLSValue, setLSValue, initLSValue, getDefaultPathname} from '../util/loginUtil';
import * as LOGIN_API from '../apis/login';

export default class LoginStore {
    // 地址栏参数
    @observable queryParams = {};
    // 升级状态。状态为0时，显示登录页，否则跳转升级页面
    @observable updatestatus = '';
    // 多语言
    @observable multiLangs = getLSValue('login', 'multiLangs') || [];
    // 登录页状态
    @observable state = objectAssign({}, {
        win_width: jQuery(window).width(),
        win_height: jQuery(window).height(),
        isLogging: false,
        hasMultiLang: false,
        multiLangVisible: false,
        loginFormItems: [],
        loginFormHiddenItems: [],
        loginSetting: {},
        validateCode: '/weaver/weaver.file.MakeValidateCode?seriesnum_=0'
    }, objectAssign({}, getLSValue('login', 'loginCache'), {
        loginType: getLSValue('login', 'loginType') || 'form',
        langId: getLSValue('login', 'langId') || '',
        langText: getLSValue('login', 'langText') || '',
        isRememberAccount: getLSValue('login', 'isRememberAccount') || false,
        isRememberPassword: getLSValue('login', 'isRememberPassword') || false,
        cacheAccount: getLSValue('login', 'cacheAccount') || '',
        cachePassword: getLSValue('login', 'cachePassword') || '',
        initialSlide: getLSValue('login', 'initialSlide') || 0,
        autoCarousel: getLSValue('login', 'autoCarousel') || false,
        carouselTime: getLSValue('login', 'carouselTime') || 3
    }));
    // 登录验证码刷新参数
    @observable seriesnum_ = 0;
    // 自定义登录页加载状态
    @observable weaCustomLoginLoaded = false;

    constructor() {
        this.onWindowResize = this.onWindowResize.bind(this);
        this.setQueryParams = this.setQueryParams.bind(this);
        this.setState = this.setState.bind(this);
        this.setStateAndCache = this.setStateAndCache.bind(this);
        this.getMultiLangs = this.getMultiLangs.bind(this);
        this.getUpgradeInfo = this.getUpgradeInfo.bind(this);
        this.getLoginInfo = this.getLoginInfo.bind(this);
        this.getLoginForm = this.getLoginForm.bind(this);
        this.getElementStyle = this.getElementStyle.bind(this);
        this.onPasswordForget = this.onPasswordForget.bind(this);
        this.onRememberChange = this.onRememberChange.bind(this);
        this.onBgImageChange = this.onBgImageChange.bind(this);
        this.onValidateCodeChange = this.onValidateCodeChange.bind(this);

        jQuery(window).resize(() => this.onWindowResize());
    }

    @computed
    get labelObj() {
        const {langId, labelInfo} = this.state;
        return labelInfo['langid' + langId] || {};
    }

    @action
    onWindowResize() {
        const width = jQuery(window).width();
        const height = jQuery(window).height();

        if (width < 800) {
            jQuery('#LoginContainer').css({'overflowX': 'scroll'});
        } else {
            jQuery('#LoginContainer').css({'overflowX': 'hidden'});
        }

        if (height < 712) {
            jQuery('#LoginContainer').css({'overflowY': 'scroll'});
        } else {
            jQuery('#LoginContainer').css({'overflowY': 'hidden'});
        }

        this.setState({
            win_width: width < 800 ? 800 : width,
            win_height: height < 712 ? 712 : height,
        });
    }

    @action
    getElementStyle(element) {
        const {win_width, win_height, loginType, loginFormItems} = this.state;
        let {showtype, isAbsolute, width, height, rate_x, rate_y, level, vertical, levelMargin, verticalMargin} = element;

        if (!width) {
            width = win_width;
        }

        if (!height) {
            height = win_height;
        }

        let style = {};
        if (isAbsolute == '1') {
            style = {
                left: (rate_x * 100) + '%',
                top: (rate_y * 100) + '%',
                width,
                height
            };
        } else {
            let left = 0;
            switch (level) {
                case 'left':
                    left = levelMargin;
                    break;
                case 'center':
                    left = (win_width - width) / 2 + levelMargin;
                    break;
                case 'right':
                    left = win_width - width - levelMargin;
                    break;
            }

            let top = 0;
            switch (vertical) {
                case 'top':
                    top = verticalMargin;
                    break;
                case 'middle':
                    top = (win_height - height) / 2 + verticalMargin;
                    break;
                case 'bottom':
                    top = win_height - height - verticalMargin;
                    break;
            }

            style = {left, top, width, height};
        }

        if (loginType == 'form') {
            const len = loginFormItems.length - 2;
            if (len) {
                if (showtype == 'loginbox') {
                    style.height += len * 65;
                    style.top -= len * 32.5;
                }
                if (showtype == 'logo' || showtype == 'loginForm' || showtype == 'qrcode') {
                    style.top -= len * 32.5;
                }
            }
        }

        return style;
    }

    @action
    setQueryParams(params = {}) {
        this.queryParams = params;
    }

    @action
    setState(state) {
        this.state = objectAssign({}, this.state, state);
    }

    @action
    setStateAndCache(key, value) {
        this.setState({[key]: value});
        setLSValue('login', key, value);
    }

    @action
    getMultiLangs(params = {}) {
        LOGIN_API.getActiveLanguage(params).then((result) => {
            if (result.status == '1') {
                const {activeLanguageInfo, activeLanguageIds, languageIdentify, systemDefaultLang = {}} = result;
                this.multiLangs = activeLanguageInfo;
                setLSValue('login', 'multiLangs', activeLanguageInfo);
                WeaTools.ls.set('activeLanguageIds', activeLanguageIds);
                WeaTools.ls.set('languageIdentify', languageIdentify);

                // 当前状态中没有语言时，取默认语言
                if (!this.state.langId) {
                    const {id:langId = '7', language:langText = '简体中文'} = systemDefaultLang;
                    this.getLoginForm({langId});
                    this.setState({langId, langText});
                }
            }
        });
    }

    @action
    getUpgradeInfo(params = {}) {
        this.queryParams = params;

        LOGIN_API.getUpgradeInfo(params).then((result) => {
            const {updatestatus, upgradeurl} = result;
            this.updatestatus = updatestatus;
            if (updatestatus == '0') {
                this.getLoginInfo(params);
            } else {
                window.location.href = upgradeurl;
            }
        });
    }

    @action
    getLoginInfo(params = {}) {
        WeaTools.ls.set('gopage', params.gopage || '');

        // LOGIN_API.checkCasIsDeployed().then((result) => {
        //     const {isDeployed, hasSession} = result;
        //     if (isDeployed && hasSession) { // 部署了CAS并且用户已登录，直接跳转登录后页面
        //         window.location.href = '/wui/index.html?#/main';
        //     }
        // });

        this.queryParams = params;
        this.updatestatus = '0';

        LOGIN_API.getLoginInfo(params).then((result) => {
            // 缓存登录日期
            const date = new Date();
            const logindate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
            WeaTools.ls.set('logindate', logindate);

            if (result.status != '2') {
                const {loginTemplateTitle = '', loginSettingInfo = {}, bgImagesInfo = [], settingversion, templateType} = result;
                const {loginInfo = {}} = loginSettingInfo;

                // 判断设置版本和缓存版本是否一致
                const _settingversion = getLSValue('login', 'settingversion');
                const isNewVersion = settingversion != _settingversion;

                // 设置浏览器窗口标题
                document.title = loginTemplateTitle;

                // 获取幻灯片默认位置
                const _loginBgImage = !isNewVersion ? getLSValue('login', 'loginBgImage') : '';
                let initialSlide = 0;
                const loginBgImage = _loginBgImage || loginInfo.imgsrc;
                for (let i = 0, len = bgImagesInfo.length; i < len; i++) {
                    if (bgImagesInfo[i].imgsrc == loginBgImage) {
                        initialSlide = i;
                        break;
                    }
                }
                setLSValue('login', 'initialSlide', initialSlide);
                // 获取幻灯片是否自动轮播
                const _autoCarousel = !isNewVersion ? getLSValue('login', 'autoCarousel') : undefined;
                const autoCarousel = _autoCarousel != undefined ? _autoCarousel : loginInfo.autoCarousel;
                setLSValue('login', 'autoCarousel', autoCarousel);
                // 获取幻灯片自动轮播间隔时间
                const _carouselTime = !isNewVersion ? getLSValue('login', 'carouselTime') : '';
                const carouselTime = _carouselTime || loginInfo.carouselTime;
                setLSValue('login', 'carouselTime', carouselTime);

                const state = objectAssign({}, result, {initialSlide, autoCarousel, carouselTime});
                setLSValue('login', 'loginCache', state);

                if (isNewVersion) {
                    if (templateType == 'ECustom') {
                        this.onLoadCustomLogin();
                    }
                    setLSValue('login', 'loginBgImage', loginInfo.imgsrc);
                    setLSValue('login', 'loginBgImageWidth', loginInfo.width);
                    setLSValue('login', 'loginBgImageHeight', loginInfo.height);
                    setLSValue('login', 'settingversion', settingversion);
                    this.setState(state);
                }
            } else {
                message.error(result.errormsg);
            }
        });
    }

    @action
    onLoadCustomLogin() {
        window.eventRegister.loadModule('f_customLogin', () => {
            setTimeout(() => this.weaCustomLoginLoaded = true, 100);
        }, () => {
        });
    }

    @action
    getLoginForm(params = {}) {
        const queryParams = this.queryParams;
        const {logintype = '1'} = queryParams;
        const {loginId = '', langId = this.state.langId} = params;

        if (langId) {
            window.doLoginAction && window.doLoginAction('getLoginForm', {
                queryParams: queryParams,
                logintype: logintype,
                loginid: loginId,
                langid: langId,
                callback: (result) => {
                    const {hasMultiLang = false, loginFormItems = [], loginFormHiddenItems = [], loginSetting = {}} = result;
                    this.setState({hasMultiLang, loginFormItems, loginFormHiddenItems, loginSetting});
                }
            });
        }
    }

    @action
    onBgImageChange(params, index) {
        const {imgsrc, width, height} = params;
        const loginInfo = objectAssign({}, this.state.loginSettingInfo.loginInfo, {imgsrc, width, height});
        const loginSettingInfo = objectAssign({}, this.state.loginSettingInfo, {loginInfo});
        this.setState({loginSettingInfo, initialSlide: index});

        setLSValue('login', 'initialSlide', index);
        setLSValue('login', 'loginBgImage', imgsrc);
        setLSValue('login', 'loginBgImageWidth', width);
        setLSValue('login', 'loginBgImageHeight', height);
    }

    @action
    onRememberChange(type, checked) {
        const {isRememberAccount, isRememberPassword} = this.state;
        if ('account' == type) {
            this.setState({
                isRememberAccount: checked,
                isRememberPassword: !checked ? checked : isRememberPassword
            });
        } else if ('password' == type) {
            this.setState({
                isRememberAccount: checked ? checked : isRememberAccount,
                isRememberPassword: checked
            });
        }
    }

    @action
    onPasswordForget(params = {}) {
        const {langId = this.state.langId} = params;
        window.doLoginAction && window.doLoginAction('forgetPassword', {langid: langId});
    };

    @action
    onValidateCodeChange() {
        setTimeout(() => this.setState({validateCode: `/weaver/weaver.file.MakeValidateCode?seriesnum_=${++this.seriesnum_}`}), 50);
    }

    @action
    onLogin() {
        this.setState({isLogging: true});
        LOGIN_API.getUpgradeInfo().then((result) => {
            const {updatestatus, upgradeurl} = result;
            this.updatestatus = updatestatus;
            if (updatestatus == '0') {
                this.doLogin();
            } else {
                window.location.href = upgradeurl;
            }
        });
    }

    @action
    doLogin() {
        const queryParams = this.queryParams;
        const {logintype = '1'} = queryParams;
        const {langId, langText, isRememberAccount, isRememberPassword, loginSetting} = this.state;

        this.setState({isLogging: true});
        window.doLoginAction && window.doLoginAction('login', {
            queryParams: queryParams,
            logintype: logintype,
            langid: langId,
            loginSetting: loginSetting,
            success: (username, password) => {
                jQuery.setSessionTimeZone && jQuery.setSessionTimeZone();

                let cacheAccount = '';
                let cachePassword = '';
                if (isRememberAccount) cacheAccount = username;
                if (isRememberPassword) cachePassword = password;
                this.setState({isRememberAccount, isRememberPassword, cacheAccount, cachePassword});

                setLSValue('login', 'langId', langId);
                setLSValue('login', 'langText', langText);
                setLSValue('login', 'cacheAccount', cacheAccount);
                setLSValue('login', 'cachePassword', cachePassword);
                setLSValue('login', 'isRememberAccount', isRememberAccount);
                setLSValue('login', 'isRememberPassword', isRememberPassword);

                initLSValue(username, langId);
                WeaTools.ls.set('languageidweaver', langId);

                // 登录成功回调
                let loginCallback = true;
                if (window.onLoginCallback && typeof window.onLoginCallback == 'function') {
                    loginCallback = window.onLoginCallback();
                }

                // 登录成功回调返回true时，继续标准跳转。
                if (loginCallback) {
                    if (logintype == '2') {
                        window.location.href = '/spa/crmPortal/mobx/index.html#/main';
                    } else {
                        // 判断当前登录日期和上次登录的日期是否为同一天，不是同一天则刷新页面
                        const date = new Date();
                        const logindate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
                        const _logindate = WeaTools.ls.getStr('logindate');
                        if (logindate != _logindate) {
                            WeaTools.ls.set('logindate', logindate);
                            window.location.href = '/wui/index.html?#/main';
                        } else {
                            // weaHistory.push({pathname: getDefaultPathname()});
                            window.location.href = '/wui/index.html?#/main';
                        }
                    }
                }

                this.setState({isLogging: false});
            },
            failure: (params = {}) => {
                if (params.reflashValidateCode) {
                    this.onValidateCodeChange();
                }
                this.getLoginForm();
                this.setState({isLogging: false});
            }
        });
    }

    @action
    onQCLogin() {
        const {langId, langText, qrcode} = this.state;

        LOGIN_API.login4qc({
            langid: langId,
            loginkey: qrcode.loginkey,
            isie: !!jQuery.browser.msie
        }).then((result) => {
            if (jQuery.trim(result) != '0' && jQuery.trim(result) != '9' && jQuery.trim(result) != '-99') {
                jQuery.setSessionTimeZone && jQuery.setSessionTimeZone();

                setLSValue('login', 'langId', langId);
                setLSValue('login', 'langText', langText);
                WeaTools.ls.set('languageidweaver', langId);

                // weaHistory.push({pathname: getDefaultPathname()});
                window.location.href = '/wui/index.html?#/main';
            }
        });
    }
}
